# 拦截器
from flask import request,abort
from flaskDemo.token.token_deal import verify_token
from flaskDemo.extensions.error import CustomExcetion
from flaskDemo.extensions.logger import MyLogger
logger = MyLogger().getLogger()
def init_interceptors(app):
    @app.before_request
    def request_before():
        url = request.path
        logger.info(f"request url {url},参数：{request.values}")
        if url == '/' or url is None:
            return '欢迎访问xxx系统'
        pass_list = ['/user/login']
        if url in pass_list:
            pass
        else:
            # 判断是否登录
            exists = exists_url(app, url)
            if exists:
                auth = request.headers.get("Authorization")
                if auth and auth.startswith("Bearer "):
                    token = auth[7:]
                    user_name = ""
                    user_name = verify_token(token)
                    if user_name:
                        pass
                else:
                    raise CustomExcetion(1001, "权限不足")
            else:
                abort(404)

# 判断路由是否在系统中已存在
def exists_url(app,url):
    url = url.replace("/", ".")
    url = url[1::]
    urls = []
    for rule in app.url_map.iter_rules():
        urls.append(rule.endpoint)
    if url in urls:
        return True
    else:
        return False
